<template>
  <div>
    <div class="container">
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="标题">
            <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
          </el-form-item>
          <el-form-item label="发布人">
            <el-input v-model="searchForm.publisher" placeholder="请输入发布人" clearable />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="searchForm.createTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="toolbar-container">
        <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd">新增</el-button>
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          批量删除
        </el-button>
      </div>

      <!-- 表格区域 -->
      <TableCustom
          :columns="columns"
          :tableData="menuData"
          row-key="id"
          :has-pagination="true"
          :selection="true"
          :pagination="pagination"
          @page-change = "handlePageChange"
          @size-change="handleSizeChange"
          @selection-change="handleSelectionChange"
          :layout="'total, sizes, prev, pager, next, jumper'"
          :viewFunc="handleView"
          :delFunc="handleDelete"
          :editFunc="handleEdit"
          :topFunc="toggleTop"
          :statusFunc="toggleStatus">
      </TableCustom>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="800px" destroy-on-close
               :close-on-click-modal="false" @close="closeDialog">
      <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData">
      </TableEdit>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="公告详情" v-model="visible1" width="800px" destroy-on-close>
      <div class="announcement-detail">
        <h2 class="announcement-title">{{ viewData.title }}</h2>
        <div class="announcement-meta">
          <span>发布人: {{ viewData.publisher }}</span>
          <span>浏览量：{{viewData.pageViews??0}}</span>
          <span>发布时间: {{ viewData.pubTime }}</span>
        </div>
        <div class="announcement-content">
          <pre>{{ viewData.content }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="system-menu">
import {ref, computed, onMounted} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CirclePlusFilled, Delete } from '@element-plus/icons-vue';
import {
  getAnnouncementList,
  getAnnouncementDetail,
  createAnnouncement,
  updateAnnouncement,
  deleteAnnouncement,
  batchDeleteAnnouncements,
  toggleTopStatus,
  togglePublishStatus
} from '@/api/announcement';


//前后端联调 调试真实的数据
const menuData = ref<any[]>([]);
// 选中的ID数组
const selectedIds = ref<number[]>([]);

// 搜索表单
const searchForm = ref({
  title: '',
  publisher: '',
  createTime: []
});

const pagination = ref({
  currentPage:1,
  pageSize:10,
  total: 0
})

// 对话框状态
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref<any>({});

// 查看详情
const visible1 = ref(false);
const viewData = ref<any>({});

// 模拟当前登录用户信息
// const currentUser = ref({
//   pubType: '管理员',
//   pubId: 1,
//   publisher: '张三'
// });


//获取公告列表
const refreshList = async () => {
  const [startTime, endTime] = searchForm.value.createTime || [];

  const params = {
    title: searchForm.value.title,
    publisher: searchForm.value.publisher,
    startTime,
    endTime,
    page: pagination.value.currentPage,
    pageSize: pagination.value.pageSize
  };

  const res = await getAnnouncementList(params);
  menuData.value = res.data.list;
  pagination.value.total = res.data.total;
};

//初始化时调用
onMounted(()=>{
  refreshList();
});

// 表格列配置
const columns = ref([
  { type: 'selection', width: 50 }, // 添加选择列
  { prop: 'id', label: 'ID', align: 'left',  },
  { prop: 'publisher', label: '发布人',  },
  { prop: 'title', label: '标题', },
  { prop: 'pubTime', label: '创建时间', },
  { prop: 'updateTime', label: '修改时间',  },
  { prop: 'operator', label: '操作', width: 400 },
]);

// 表单配置
const options = ref({
  labelWidth: '100px',
  span: 24,
  list: [
    { type: 'input', label: '标题', prop: 'title', required: true },
    {
      type: 'input',
      label: '发布内容',
      prop: 'content',
      required: true,
      attrs: {
        type: 'textarea',
        rows: 15,
        resize: 'none',
        style: 'font-family: monospace; white-space: pre;'
      }
    },
  ]
});

// 搜索
const handleSearch = () => {
  pagination.value.currentPage = 1;
  refreshList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    publisher: '',
    createTime: []
  };
  pagination.value.currentPage = 1;
  refreshList();
};

const handlePageChange = (page: number) => {
  pagination.value.currentPage = page;
  refreshList();
};

const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  refreshList();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id);
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  ElMessageBox.confirm('确定要删除选中的数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await batchDeleteAnnouncements(selectedIds.value);
    ElMessage.success('删除成功');
    await refreshList();
  }).catch(() => {
    // 用户取消操作
  });
};

// 新增
const handleAdd = () => {
  rowData.value = {
    // publisher: currentUser.value.publisher,
    title: '',
    content: '',
    // pubType: currentUser.value.pubType,
    // pubId: currentUser.value.pubId,
  };
  isEdit.value = false;
  visible.value = true;
};

// 编辑
const handleEdit = (row: any) => {
  rowData.value = { ...row };
  isEdit.value = true;
  visible.value = true;
};

// 更新数据
const updateData = async () =>{

  if (isEdit.value) {
    const data = { ...rowData.value };
    delete data.pubTime;
    delete data.updateTime;

    await updateAnnouncement(data);
    ElMessage.success('编辑成功');
  } else {
    await createAnnouncement({
      ...rowData.value,
      // pubType: currentUser.value.pubType,
      // pubId: currentUser.value.pubId,
    });
    ElMessage.success('新增成功');
  }

  visible.value = false;
  await refreshList();

};

// 关闭对话框
const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

// 查看详情
const handleView = async (row: any) => {
  const res = await getAnnouncementDetail(row.id);
  viewData.value = res.data;
  visible1.value = true;
  console.log('详情数据',res.data)
};

// 删除单条数据
const handleDelete = async (row: any) => {
  await deleteAnnouncement(row.id);
  ElMessage.success('删除成功');
  await refreshList();
};

// 置顶 / 撤销置顶
const toggleTop = async (row: any) => {
  const newTop = row.isTop === 1 ? 0 : 1;
  const actionText = newTop === 1 ? '置顶' : '撤销置顶';

  ElMessageBox.confirm(
      `确定要${actionText}该公告吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    await toggleTopStatus({ id: row.id, isTop: newTop });
    ElMessage.success(`${actionText}成功`);
    await refreshList();
  }).catch(() => {
    // 用户取消操作，不做任何处理
  });
};


// 发布 / 隐藏公告
const toggleStatus = async (row: any) => {
  const newStatus = row.status === '生效' ? '过期' : '生效';
  const actionText = newStatus === '生效' ? '发布' : '隐藏';

  ElMessageBox.confirm(
      `确定要${actionText}该公告吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    await togglePublishStatus({ id: row.id, status: newStatus });
    ElMessage.success(`${actionText}成功`);
    await refreshList();
  }).catch(() => {
    // 用户取消操作
  });
};



</script>

<style scoped>
.search-container {
  padding: 20px;
  background: #fff;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-container {
  margin-bottom: 20px;
  text-align: right;
}

.announcement-detail {
  padding: 20px;
}

.announcement-title {
  font-size: 24px;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

.announcement-meta span {
  margin-right: 30px;
}

.announcement-meta {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.announcement-content {
  font-size: 16px;
  line-height: 1.8;
  white-space: pre-wrap;
  background: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
  font-family: inherit;
}

.announcement-content pre {
  white-space: pre-wrap;
  font-family: inherit;
  margin: 0;
}
</style>
